package org.jeecg.modules.commu;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.boot.starter.rabbitmq.listenter.MqListener;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.common.base.BaseMap;
import org.jeecg.modules.device.*;
import org.jeecg.modules.service.DeviceService;
import org.jeecg.modules.service.ITigDeviceService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

@Slf4j
@RabbitComponent(value = "deviceConnetListner1")
public class RabbitMqDeviceConnetListner extends BaseRabbiMqHandler<BaseMap> {

    @Autowired
    DeviceContainer deviceContainer;

    @Autowired
    DeviceService deviceService;

    @Autowired
    ITigDeviceService iTigDeviceService;

    @RabbitListener(queues = "deviceReConnect")
    public void onMessage(BaseMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<BaseMap>() {
            @Override
            public void handler(BaseMap map, Channel channel) {
                try {
                    String deviceId = map.get("deviceId");
                    if (deviceId == null) return;

                    //判断接收到处理消息的时候设备是否已经从数据库删除了
                    if (iTigDeviceService.getById(deviceId) == null){
                        log.error("deviceReConnect Error Msg:device id = " + deviceId + "has been delete,you can't get it again");
                        return;
                    }
                    deviceService.login(deviceId,false);
                    return;
                }catch (Exception e){
                    log.error(e.getStackTrace().toString());
                }
            }
        });
    }

}
